<?php

namespace app\core\services\user;

use app\core\entities\User;
use app\core\forms\user\LoginSmartForm;
use app\core\repositories\user\UserRepository;
use DomainException;

class AuthService
{
    private UserRepository $user_repository;

    public function __construct(UserRepository $user_repository)
    {
        $this->user_repository = $user_repository;
    }

    public function smartAuth(LoginSmartForm $form): User
    {
        $user = $this->user_repository->findByEmail($form->email);
        if (!$user || !$user->validatePassword($form->password)) {
            throw new DomainException('Не найден пользователи или ошибка в пароле');
        }

//        if ($user->usedFactor2()) {
//            if (!$form->factor2) {
//                throw new DomainException(Yii::t('user', 'Fill code from authenticator app'));
//            }
//            $ga = new GoogleAuthenticator();
//            $checkResult = $ga->verifyCode($user->factor2_code, $form->factor2, 2);
//            if (!$checkResult) {
//                throw new DomainException(Yii::t('user', 'Code expired'));
//            }
//        }

        if (!$user->isActive()) {
            $user->status = User::STATUS_ACTIVE;
            $this->user_repository->save($user);
        }
        return $user;
    }
}